/*
 * semaphore.cpp
 *
 *  Created on: 10/11/2011
 *      Author: joagf
 */

#include "semaphore.h"

void init_semaphore(Semaphore *s,int n)
{
        s->num = n;
        pthread_mutex_init(&(s->mutex),NULL);
        pthread_mutex_init(&(s->mutex_num),NULL);
        if (n == 0)
        {
                pthread_mutex_lock(&(s->mutex));
        }
}

void down(Semaphore *s)
{
        pthread_mutex_lock(&(s->mutex_num));

        if ( s->num <= 1)
        {
                s->num--;
                pthread_mutex_unlock(&(s->mutex_num));
                pthread_mutex_lock(&(s->mutex));
        }
        else
        {
                s->num--;
                pthread_mutex_unlock(&(s->mutex_num));
        }
}


void up(Semaphore *s)
{
        pthread_mutex_lock(&(s->mutex_num));
        if (s->num <= 0)/*se existe fila*/
        {
                pthread_mutex_unlock(&(s->mutex));
        }
        s->num++;
        pthread_mutex_unlock(&(s->mutex_num));

}

void destroy(Semaphore *s)
{
        pthread_mutex_destroy(&(s->mutex));
        pthread_mutex_destroy(&(s->mutex_num));
}
